import { useRef, useCallback } from 'react';

function useFrameTimer() {
  const timerRef = useRef(null);

  const lastValueRef = useRef(null);

  const valueQueue = useRef([]).current;

  const Enqueue = useCallback((val) => {
    const intVal = Math.round(val * 100);
    if (!valueQueue.includes(intVal)) {
      valueQueue.push(intVal);
    }
  }, []);

  const Dequeue = () => {
    while (valueQueue.length > 1) {
      valueQueue.shift();
    }
    if (valueQueue.length > 0) {
      const val = valueQueue.shift();
      if (val !== lastValueRef.current) {
        lastValueRef.current = val;
        return val;
      }
    }
    return null;
  };

  const StartTimer = (callback) => {
    timerRef.current = setInterval(() => {
      const val = Dequeue();
      if (val !== null) {
        callback(val / 100.0);
      }
    }, 20);
  };

  const ExitTimer = () => {
    clearInterval(timerRef.current);
    timerRef.current = null;
  };

  return { Enqueue, Dequeue, StartTimer, ExitTimer };
}

export default useFrameTimer;
